package storage

import (
	"5title_gin/config"
	myMinio "5title_gin/pkg/storage/minio"
	"context"
	"fmt"
	"github.com/minio/minio-go/v7"
	"github.com/minio/minio-go/v7/pkg/credentials"
	"go.uber.org/zap"
	"io"
)

type Storage interface {
	UploadFile(ctx context.Context, file io.Reader, key string, contentType string) (string, error)
	DownloadFile(ctx context.Context, key string, w io.Writer) error
	DeleteFile(ctx context.Context, key string) error
}

type storageImpl struct {
	storage Storage
}

func NewStorage(cfg *config.Config) (Storage, error) {
	//zap.S().Infof("Loaded storage config: %+v", cfg.Storage)
	switch cfg.Storage.Type {
	case "minio":
		opts := myMinio.Options{
			Endpoint:     cfg.Storage.Endpoint,
			Creds:        credentials.NewStaticV4(cfg.Storage.AccessKey, cfg.Storage.SecretKey, ""),
			Secure:       cfg.Storage.Secure,
			Region:       cfg.Storage.Region,
			BucketLookup: minio.BucketLookupAuto,
			Bucket:       cfg.Storage.Bucket,
		}
		_, err := myMinio.NewMinioClient(opts)
		if err != nil {
			zap.S().Errorf("Failed to initialize Minio client: %v", err)
			return nil, err
		}
		zap.S().Infof("📦%s 配置成功！", cfg.Storage.Type)
		return myMinio.NewMinioClient(opts)
	case "s3":
		zap.S().Infof("📦%s 配置成功！", cfg.Storage.Type)
		return nil, fmt.Errorf("s3 storage not implemented")
	case "local":
		zap.S().Infof("📦%s 配置成功！", cfg.Storage.Type)
		return nil, fmt.Errorf("local storage not implemented") // 使用 Bucket 作为根目录
	default:
		return nil, fmt.Errorf("unsupported storage type: %s", cfg.Storage.Type)
	}
}

func (s *storageImpl) UploadFile(ctx context.Context, file io.Reader, key string, contentType string) (string, error) {
	return s.storage.UploadFile(ctx, file, key, contentType)
}

func (s *storageImpl) DownloadFile(ctx context.Context, key string, w io.Writer) error {
	return s.storage.DownloadFile(ctx, key, w)
}

func (s *storageImpl) DeleteFile(ctx context.Context, key string) error {
	return s.storage.DeleteFile(ctx, key)
}
